<!DOCTYPE html>
<html lang="zh" dir="ltr" class="client-nojs">
<head>
<title>派生类</title>
<meta charset="UTF-8">
<meta name="generator" content="MediaWiki 1.21.2">
<link rel="shortcut icon" href="../../../common/favicon.ico">
<link rel="stylesheet" href="../../../common/ext.css">
<meta name="ResourceLoaderDynamicStyles" content="">
<link rel="stylesheet" href="../../../common/site_modules.css">
<style>a:lang(ar),a:lang(ckb),a:lang(fa),a:lang(kk-arab),a:lang(mzn),a:lang(ps),a:lang(ur){text-decoration:none}#toc{display:none}.editsection{display:none}
/* cache key: mwiki1-mwiki_zh_:resourceloader:filter:minify-css:7:15cea3ec788a65b5187d4018eed543bf */</style>

<script src="../../../common/startup_scripts.js"></script>
<script>if(window.mw){
mw.config.set({"wgCanonicalNamespace":"","wgCanonicalSpecialPageName":false,"wgNamespaceNumber":0,"wgPageName":"cpp/language/derived_class","wgTitle":"cpp/language/derived class","wgCurRevisionId":72405,"wgArticleId":9252,"wgIsArticle":true,"wgAction":"view","wgUserName":null,"wgUserGroups":["*"],"wgCategories":[],"wgBreakFrames":false,"wgPageContentLanguage":"zh","wgSeparatorTransformTable":["",""],"wgDigitTransformTable":["",""],"wgDefaultDateFormat":"zh","wgMonthNames":["","1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],"wgMonthNamesShort":["","1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],"wgRelevantPageName":"cpp/language/derived_class","wgUserVariant":"zh","wgRestrictionEdit":[],"wgRestrictionMove":[]});
}</script><script>if(window.mw){
mw.loader.implement("user.options",function(){mw.user.options.set({"ccmeonemails":0,"cols":80,"date":"default","diffonly":0,"disablemail":0,"disablesuggest":0,"editfont":"default","editondblclick":0,"editsection":0,"editsectiononrightclick":0,"enotifminoredits":0,"enotifrevealaddr":0,"enotifusertalkpages":1,"enotifwatchlistpages":0,"extendwatchlist":0,"externaldiff":0,"externaleditor":0,"fancysig":0,"forceeditsummary":0,"gender":"unknown","hideminor":0,"hidepatrolled":0,"imagesize":2,"justify":0,"math":1,"minordefault":0,"newpageshidepatrolled":0,"nocache":0,"noconvertlink":0,"norollbackdiff":0,"numberheadings":0,"previewonfirst":0,"previewontop":1,"quickbar":5,"rcdays":7,"rclimit":50,"rememberpassword":0,"rows":25,"searchlimit":20,"showhiddencats":0,"showjumplinks":1,"shownumberswatching":1,"showtoc":0,"showtoolbar":1,"skin":"cppreference2","stubthreshold":0,"thumbsize":2,"underline":2,"uselivepreview":0,"usenewrc":0,"watchcreations":0,"watchdefault":0,"watchdeletion":0,
"watchlistdays":3,"watchlisthideanons":0,"watchlisthidebots":0,"watchlisthideliu":0,"watchlisthideminor":0,"watchlisthideown":0,"watchlisthidepatrolled":0,"watchmoves":0,"wllimit":250,"variant":"zh","language":"zh","searchNs0":true,"searchNs1":false,"searchNs2":false,"searchNs3":false,"searchNs4":false,"searchNs5":false,"searchNs6":false,"searchNs7":false,"searchNs8":false,"searchNs9":false,"searchNs10":false,"searchNs11":false,"searchNs12":false,"searchNs13":false,"searchNs14":false,"searchNs15":false,"gadget-MathJax":1,"gadget-ColiruCompiler":1});;},{},{});mw.loader.implement("user.tokens",function(){mw.user.tokens.set({"editToken":"+\\","patrolToken":false,"watchToken":false});;},{},{});
/* cache key: mwiki1-mwiki_zh_:resourceloader:filter:minify-js:7:258d7cd6aa9aa67dee25e01fb6a9e505 */
}</script>
<script>if(window.mw){
mw.loader.load(["mediawiki.page.startup","mediawiki.legacy.wikibits","mediawiki.legacy.ajax"]);
}</script>
<style type="text/css">/*<![CDATA[*/
.source-cpp {line-height: normal;}
.source-cpp li, .source-cpp pre {
	line-height: normal; border: 0px none white;
}
/**
 * GeSHi Dynamically Generated Stylesheet
 * --------------------------------------
 * Dynamically generated stylesheet for cpp
 * CSS class: source-cpp, CSS id: 
 * GeSHi (C) 2004 - 2007 Nigel McNie, 2007 - 2008 Benny Baumann
 * (http://qbnz.com/highlighter/ and http://geshi.org/)
 * --------------------------------------
 */
.cpp.source-cpp .de1, .cpp.source-cpp .de2 {font: normal normal 1em/1.2em monospace; margin:0; padding:0; background:none; vertical-align:top;}
.cpp.source-cpp  {font-family:monospace;}
.cpp.source-cpp .imp {font-weight: bold; color: red;}
.cpp.source-cpp li, .cpp.source-cpp .li1 {font-weight: normal; vertical-align:top;}
.cpp.source-cpp .ln {width:1px;text-align:right;margin:0;padding:0 2px;vertical-align:top;}
.cpp.source-cpp .li2 {font-weight: bold; vertical-align:top;}
.cpp.source-cpp .kw1 {color: #0000dd;}
.cpp.source-cpp .kw2 {color: #0000ff;}
.cpp.source-cpp .kw3 {color: #0000dd;}
.cpp.source-cpp .kw4 {color: #0000ff;}
.cpp.source-cpp .co1 {color: #909090;}
.cpp.source-cpp .co2 {color: #339900;}
.cpp.source-cpp .coMULTI {color: #ff0000; font-style: italic;}
.cpp.source-cpp .es0 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es1 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es2 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es3 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es4 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es5 {color: #008000; font-weight: bold;}
.cpp.source-cpp .br0 {color: #008000;}
.cpp.source-cpp .sy0 {color: #008000;}
.cpp.source-cpp .sy1 {color: #000080;}
.cpp.source-cpp .sy2 {color: #000040;}
.cpp.source-cpp .sy3 {color: #000040;}
.cpp.source-cpp .sy4 {color: #008080;}
.cpp.source-cpp .st0 {color: #008000;}
.cpp.source-cpp .nu0 {color: #000080;}
.cpp.source-cpp .nu6 {color: #000080;}
.cpp.source-cpp .nu8 {color: #000080;}
.cpp.source-cpp .nu12 {color: #000080;}
.cpp.source-cpp .nu16 {color:#000080;}
.cpp.source-cpp .nu17 {color:#000080;}
.cpp.source-cpp .nu18 {color:#000080;}
.cpp.source-cpp .nu19 {color:#000080;}
.cpp.source-cpp .ln-xtra, .cpp.source-cpp li.ln-xtra, .cpp.source-cpp div.ln-xtra {background-color: #ffc;}
.cpp.source-cpp span.xtra { display:block; }

/*]]>*/
</style><!--[if lt IE 7]><style type="text/css">body{behavior:url("/mwiki/skins/cppreference2/csshover.min.htc")}</style><![endif]--></head>
<body class="mediawiki ltr sitedir-ltr ns-0 ns-subject page-cpp_language_derived_class skin-cppreference2 action-view cpp-navbar">
        <!-- header -->
        <!-- /header -->
        <!-- content -->
<div id="cpp-content-base">
            <div id="content">
                <a id="top"></a>
                <div id="mw-js-message" style="display:none;"></div>
                                <!-- firstHeading -->
<h1 id="firstHeading" class="firstHeading">派生类</h1>
                <!-- /firstHeading -->
                <!-- bodyContent -->
                <div id="bodyContent">
                                        <!-- tagline -->
                    <div id="siteSub">来自cppreference.com</div>
                    <!-- /tagline -->
                                        <!-- subtitle -->
                    <div id="contentSub"><span class="subpages">&lt; <a href="../../cpp.html" title="cpp">cpp</a>‎ | <a href="../language.html" title="cpp/language">language</a></span></div>
                    <!-- /subtitle -->
                                                            <!-- bodycontent -->
                    <div id="mw-content-text" lang="zh" dir="ltr" class="mw-content-ltr"><div class="t-navbar" style=""><div class="t-navbar-sep"> </div><div class="t-navbar-head"><a href="../../cpp.html" title="cpp"> C++</a><div class="t-navbar-menu"><div><div><table class="t-nv-begin" cellpadding="0" style="line-height:1.1em">
<tr class="t-nv"><td colspan="5"> <a href="../language.html" title="cpp/language">语言</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../header.html" title="cpp/header">标准库头文件</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../freestanding.html" title="cpp/freestanding"> 自立与有宿主实现</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../named_req.html" title="cpp/named req">具名要求</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../utility.html#.E8.AF.AD.E8.A8.80.E6.94.AF.E6.8C.81" title="cpp/utility">语言支持库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../concepts.html" title="cpp/concepts">概念库</a> <span class="t-mark-rev t-since-cxx20">(C++20)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../error.html" title="cpp/error">诊断库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../utility.html" title="cpp/utility">工具库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../string.html" title="cpp/string">字符串库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../container.html" title="cpp/container">容器库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../iterator.html" title="cpp/iterator">迭代器库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../ranges.html" title="cpp/ranges"> 范围库</a> <span class="t-mark-rev t-since-cxx20">(C++20)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../algorithm.html" title="cpp/algorithm">算法库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../numeric.html" title="cpp/numeric">数值库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../locale.html" title="cpp/locale">本地化库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../io.html" title="cpp/io">输入/输出库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../filesystem.html" title="cpp/filesystem">文件系统库</a> <span class="t-mark-rev t-since-cxx17">(C++17)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../regex.html" title="cpp/regex">正则表达式库</a> <span class="t-mark-rev t-since-cxx11">(C++11)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../atomic.html" title="cpp/atomic">原子操作库</a> <span class="t-mark-rev t-since-cxx11">(C++11)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../thread.html" title="cpp/thread">线程支持库</a> <span class="t-mark-rev t-since-cxx11">(C++11)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../experimental.html" title="cpp/experimental">技术规范</a> </td></tr>
</table></div><div></div></div></div></div><div class="t-navbar-sep"> </div><div class="t-navbar-head"><a href="../language.html" title="cpp/language">C++ 语言</a></div><div class="t-navbar-sep"> </div><div class="t-navbar-head"><a href="classes.html" title="cpp/language/classes">类</a><div class="t-navbar-menu"><div><div style="display:inline-block">
<div><table class="t-nv-begin" cellpadding="0" style="line-height:1.1em">
<tr class="t-nv-h2"><td colspan="5">概述</td></tr>
<tr class="t-nv"><td colspan="5"> <a href="classes.html" title="cpp/language/classes">综述</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="class.html" title="cpp/language/class"><code>class</code>/<code>struct</code> 类型</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="union.html" title="cpp/language/union"><code>union</code> 类型</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="injected-class-name.html" title="cpp/language/injected-class-name">注入类名</a> </td></tr>
<tr class="t-nv-h2"><td colspan="5">成员</td></tr>
<tr class="t-nv"><td colspan="5"> <a href="data_members.html" title="cpp/language/data members">数据成员</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="static.html" title="cpp/language/static">静态成员</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="this.html" title="cpp/language/this"><code>this</code> 指针</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="nested_classes.html" title="cpp/language/nested types">嵌套类</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="member_template.html" title="cpp/language/member template">成员模板</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="bitfield.html" title="cpp/language/bit field">位域</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="using_declaration.html" title="cpp/language/using declaration"><code>using</code> 声明</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="member_functions.html" title="cpp/language/member functions">成员函数</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="access.html" title="cpp/language/access">成员访问指定符</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="initializer_list.html" title="cpp/language/constructor">构造函数与成员初始化器列表</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="data_members.html#.E6.88.90.E5.91.98.E5.88.9D.E5.A7.8B.E5.8C.96" title="cpp/language/data members">默认成员初始化器</a><span class="t-mark-rev t-since-cxx11">(C++11)</span></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="friend.html" title="cpp/language/friend"><code>friend</code> 说明符</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="explicit.html" title="cpp/language/explicit"><code>explicit</code> 说明符</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="converting_constructor.html" title="cpp/language/converting constructor">转换构造函数</a></td></tr>
<tr class="t-nv-h2"><td colspan="5">特殊成员函数</td></tr>
<tr class="t-nv"><td colspan="5"> <a href="default_constructor.html" title="cpp/language/default constructor">默认构造函数</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="copy_constructor.html" title="cpp/language/copy constructor">复制构造函数</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="move_constructor.html" title="cpp/language/move constructor">移动构造函数</a><span class="t-mark-rev t-since-cxx11">(C++11)</span></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="copy_assignment.html" title="cpp/language/copy assignment">复制赋值运算符</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="move_assignment.html" title="cpp/language/move assignment">移动赋值运算符</a><span class="t-mark-rev t-since-cxx11">(C++11)</span></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="destructor.html" title="cpp/language/destructor">析构函数</a></td></tr>
<tr class="t-nv-h2"><td colspan="5">继承</td></tr>
<tr class="t-nv"><td colspan="5"> <strong class="selflink">基与派生类</strong></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="ebo.html" title="cpp/language/ebo">空基类优化</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="virtual.html" title="cpp/language/virtual">虚成员函数</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="abstract_class.html" title="cpp/language/abstract class">纯虚函数与抽象类</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="override.html" title="cpp/language/override"><tt>override</tt></a><span class="t-mark-rev t-since-cxx11">(C++11)</span></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="final.html" title="cpp/language/final"><tt>final</tt></a><span class="t-mark-rev t-since-cxx11">(C++11)</span></td></tr>
</table></div>
</div><div></div></div></div></div><div class="t-navbar-sep"> </div></div>
<p>任何类类型（无论是以 <span class="t-spar">类关键词</span> <code>class</code> 还是 <code>struct</code> 声明）均可被声明为<i>派生于</i>一个或多个<i>基类</i>，各基类也可以派生自其自身的基类，组成继承层级结构。
</p><p>基类的列表在<a href="class.html" title="cpp/language/class">类声明语法</a>的 <span class="t-spar">基类子句</span> 中提供。<span class="t-spar">基类子句</span> 由字符 <code><b>:</b></code> 后随一或多个 <span class="t-spar">基类说明符</span> 的逗号分隔列表组成。
</p>
<table class="t-sdsc-begin">

<tr>
<td colspan="10" class="t-sdsc-sep">
</td></tr>
<tr class="t-sdsc">
<td class="t-sdsc-nopad"> <span class="t-spar">属性</span><span class="t-mark">(可选)</span> <span class="t-spar">访问说明符</span><span class="t-mark">(可选)</span> <span class="t-spar">虚说明符</span><span class="t-mark">(可选)</span> <span class="t-spar">类或-decltype</span>
</td>
<td class="t-sdsc-nopad">
</td>
<td class="t-sdsc-nopad">
</td></tr>



<tr>
<td colspan="10" class="t-sdsc-sep">
</td></tr></table>
<table class="t-par-begin">


<tr class="t-par">
<td>  <span class="t-spar">属性</span>
</td>
<td> -
</td>
<td>  <span class="t-mark-rev t-since-cxx11">(C++11 起)</span> 可选的任意数量<a href="attributes.html" title="cpp/language/attributes">属性</a>的序列
</td></tr>
<tr class="t-par">
<td>  <span class="t-spar">访问说明符</span>
</td>
<td> -
</td>
<td>  <code>private</code>、<code>public</code> 或 <code>protected</code> 之一
</td></tr>
<tr class="t-par">
<td>  <span class="t-spar">虚说明符</span>
</td>
<td> -
</td>
<td>  关键词 <code>virtual</code>
</td></tr>
<tr class="t-par">
<td>  <span class="t-spar">类或-decltype</span>
</td>
<td> -
</td>
<td>  以下之一：
<ul><li> <span class="t-spar">嵌套名说明符</span><span class="t-mark">(可选)</span> <span class="t-spar">类型名</span>
</li><li> <span class="t-spar">嵌套名说明符</span> <code><b>template</b></code> <span class="t-spar">简单模板标识</span>
</li></ul>
 <table class="t-rev-begin">
<tr class="t-rev t-since-cxx11"><td>
<ul><li> <a href="decltype.html" title="cpp/language/decltype"><span class="t-spar">decltype-说明符</span></a>
</li></ul>
</td>
<td><span class="t-mark-rev t-since-cxx11">(C++11 起)</span></td></tr>
</table>
</td></tr></table>
<p><span class="t-spar">虚说明符</span> 与 <span class="t-spar">访问说明符</span> 可以以任意顺序出现。由于语法限制，<a href="elaborated_type_specifier.html" title="cpp/language/elaborated type specifier">详述类型说明符</a>不能直接作为 <span class="t-spar">类或-decltype</span> 出现。
</p>
 <table class="t-rev-begin">
<tr class="t-rev t-since-cxx11"><td>
<p><span class="t-spar">基类子句</span> 中的 <span class="t-spar">基类说明符</span> 可以是<a href="parameter_pack.html" title="cpp/language/parameter pack">包展开</a>。
</p><p><span class="t-spar">类或-decltype</span> 不能指代声明为 <a href="final.html" title="cpp/language/final"><code>final</code></a> 的类或结构体。
</p>
</td>
<td><span class="t-mark-rev t-since-cxx11">(C++11 起)</span></td></tr>
</table>
<p>如果省略 <span class="t-spar">访问说明符</span>，那么它对以 <span class="t-spar">类关键词</span> <code>struct</code> 声明的类默认为 <code>public</code>，对以 <span class="t-spar">类关键词</span> <code>class</code> 声明的类为 <code>private</code>。
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="kw1">struct</span> Base <span class="br0">{</span>
    <span class="kw4">int</span> a, b, c<span class="sy4">;</span>
<span class="br0">}</span><span class="sy4">;</span>
<span class="co1">// 每个 Derived 类型对象包含一个 Base 子对象</span>
<span class="kw1">struct</span> Derived <span class="sy4">:</span> Base <span class="br0">{</span>
    <span class="kw4">int</span> b<span class="sy4">;</span>
<span class="br0">}</span><span class="sy4">;</span>
<span class="co1">// 每个 Derived2 类型对象包含 Derived 与 Base 子对象</span>
<span class="kw1">struct</span> Derived2 <span class="sy4">:</span> Derived <span class="br0">{</span>
    <span class="kw4">int</span> c<span class="sy4">;</span>
<span class="br0">}</span><span class="sy4">;</span></pre></div></div>
<p>在 <span class="t-spar">基类子句</span> 中列出的 <span class="t-spar">类或-decltype</span> 所指代的类是直接基类。它们的基类是间接基类。同一类不能被多次指定为直接基类，但同一类可以既是直接又是间接基类。
</p><p>每个直接和间接基类都作为<i>基类子对象</i>，以依赖于 ABI 的偏移量存在于派生类的对象表示中。因为<a href="ebo.html" title="cpp/language/ebo">空基类优化</a>，空基类通常不会增加派生类对象的大小。基类子对象的构造函数被派生类的构造函数所调用：可以在<a href="initializer_list.html" title="cpp/language/initializer list" class="mw-redirect">成员初始化器列表</a>中向这些构造函数提供实参。
</p>
<h3><span class="mw-headline" id=".E8.99.9A.E5.9F.BA.E7.B1.BB">虚基类</span></h3>
<p>对于每个指定为 <code>virtual</code> 的不同基类，最终派生对象中仅含有该类型的一个基类子对象，即使该类在继承层级中出现多次也是如此（只要它每次都以 <code>virtual</code> 继承）。
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="kw1">struct</span> B <span class="br0">{</span> <span class="kw4">int</span> n<span class="sy4">;</span> <span class="br0">}</span><span class="sy4">;</span>
<span class="kw1">class</span> X <span class="sy4">:</span> <span class="kw1">public</span> <span class="kw1">virtual</span> B <span class="br0">{</span><span class="br0">}</span><span class="sy4">;</span>
<span class="kw1">class</span> Y <span class="sy4">:</span> <span class="kw1">virtual</span> <span class="kw1">public</span> B <span class="br0">{</span><span class="br0">}</span><span class="sy4">;</span>
<span class="kw1">class</span> Z <span class="sy4">:</span> <span class="kw1">public</span> B <span class="br0">{</span><span class="br0">}</span><span class="sy4">;</span>
<span class="co1">// 每个 AA 类型对象拥有一个 X，一个 Y，一个 Z 和两个 B：</span>
<span class="co1">// 一个是 Z 的基类，另一个由 X 与 Y 所共享</span>
<span class="kw1">struct</span> AA <span class="sy4">:</span> X, Y, Z <span class="br0">{</span>
    <span class="kw4">void</span> f<span class="br0">(</span><span class="br0">)</span> <span class="br0">{</span>
        X<span class="sy4">::</span><span class="me2">n</span> <span class="sy1">=</span> <span class="nu0">1</span><span class="sy4">;</span> <span class="co1">// 修改虚 B 子对象的成员</span>
        Y<span class="sy4">::</span><span class="me2">n</span> <span class="sy1">=</span> <span class="nu0">2</span><span class="sy4">;</span> <span class="co1">// 修改同一虚 B 子对象的成员</span>
        Z<span class="sy4">::</span><span class="me2">n</span> <span class="sy1">=</span> <span class="nu0">3</span><span class="sy4">;</span> <span class="co1">// 修改非虚 B 子对象的成员</span>
 
        <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> X<span class="sy4">::</span><span class="me2">n</span> <span class="sy1">&lt;&lt;</span> Y<span class="sy4">::</span><span class="me2">n</span> <span class="sy1">&lt;&lt;</span> Z<span class="sy4">::</span><span class="me2">n</span> <span class="sy1">&lt;&lt;</span> <span class="st0">'<span class="es1">\n</span>'</span><span class="sy4">;</span> <span class="co1">// 打印 223</span>
    <span class="br0">}</span>
<span class="br0">}</span><span class="sy4">;</span></pre></div></div>
<p>继承层级有虚基类的例子之一是标准库的 iostream 的继承层级：<span class="t-lc"><a href="../io/basic_istream.html" title="cpp/io/basic istream">std::istream</a></span> 与 <span class="t-lc"><a href="../io/basic_ostream.html" title="cpp/io/basic ostream">std::ostream</a></span> 使用虚继承从 <span class="t-lc"><a href="../io/basic_ios.html" title="cpp/io/basic ios">std::ios</a></span> 派生。<span class="t-lc"><a href="../io/basic_iostream.html" title="cpp/io/basic iostream">std::iostream</a></span> 同时派生于 <span class="t-lc"><a href="../io/basic_istream.html" title="cpp/io/basic istream">std::istream</a></span> 和 <span class="t-lc"><a href="../io/basic_ostream.html" title="cpp/io/basic ostream">std::ostream</a></span>，所以每个 <span class="t-lc"><a href="../io/basic_iostream.html" title="cpp/io/basic iostream">std::iostream</a></span> 实例含有一个 <span class="t-lc"><a href="../io/basic_ostream.html" title="cpp/io/basic ostream">std::ostream</a></span> 子对象、一个 <span class="t-lc"><a href="../io/basic_istream.html" title="cpp/io/basic istream">std::istream</a></span> 子对象和只有一个 <span class="t-lc"><a href="../io/basic_ios.html" title="cpp/io/basic ios">std::ios</a></span> 子对象（因此也只有一个 <span class="t-lc"><a href="../io/ios_base.html" title="cpp/io/ios base">std::ios_base</a></span>）。
</p><p>所有虚基类子对象都在任何非虚基类子对象之前初始化，所以只有最终派生类会在它的<a href="initializer_list.html" title="cpp/language/initializer list" class="mw-redirect">成员初始化器列表</a>中调用虚基类的构造函数：
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="kw1">struct</span> B <span class="br0">{</span>
    <span class="kw4">int</span> n<span class="sy4">;</span>
    B<span class="br0">(</span><span class="kw4">int</span> x<span class="br0">)</span> <span class="sy4">:</span> n<span class="br0">(</span>x<span class="br0">)</span> <span class="br0">{</span><span class="br0">}</span>
<span class="br0">}</span><span class="sy4">;</span>
<span class="kw1">struct</span> X <span class="sy4">:</span> <span class="kw1">virtual</span> B <span class="br0">{</span> X<span class="br0">(</span><span class="br0">)</span> <span class="sy4">:</span> B<span class="br0">(</span><span class="nu0">1</span><span class="br0">)</span> <span class="br0">{</span><span class="br0">}</span> <span class="br0">}</span><span class="sy4">;</span>
<span class="kw1">struct</span> Y <span class="sy4">:</span> <span class="kw1">virtual</span> B <span class="br0">{</span> Y<span class="br0">(</span><span class="br0">)</span> <span class="sy4">:</span> B<span class="br0">(</span><span class="nu0">2</span><span class="br0">)</span> <span class="br0">{</span><span class="br0">}</span> <span class="br0">}</span><span class="sy4">;</span>
<span class="kw1">struct</span> AA <span class="sy4">:</span> X, Y     <span class="br0">{</span> AA<span class="br0">(</span><span class="br0">)</span> <span class="sy4">:</span> B<span class="br0">(</span><span class="nu0">3</span><span class="br0">)</span>, X<span class="br0">(</span><span class="br0">)</span>, Y<span class="br0">(</span><span class="br0">)</span> <span class="br0">{</span><span class="br0">}</span> <span class="br0">}</span><span class="sy4">;</span>
 
<span class="co1">// AA 的默认构造函数调用 X 和 Y 的默认构造函数</span>
<span class="co1">// 但这些构造函数不调用 B 的构造函数，因为 B 是虚基类</span>
AA a<span class="sy4">;</span> <span class="co1">// a.n == 3</span>
<span class="co1">// X 的默认构造函数调用 B 的构造函数</span>
X x<span class="sy4">;</span> <span class="co1">// x.n == 1</span></pre></div></div>
<p>涉及虚继承时，对类成员的无限定名字查找有<a href="unqualified_lookup.html#.E6.88.90.E5.91.98.E5.87.BD.E6.95.B0.E7.9A.84.E5.AE.9A.E4.B9.89" title="cpp/language/unqualified lookup">特殊规则</a>（有时被称为“优先性（dominance）规则”）。
</p>
<h3><span class="mw-headline" id=".E5.85.AC.E5.BC.80.E7.BB.A7.E6.89.BF">公开继承</span></h3>
<p>当类使用 <code>public</code> <a href="access.html" title="cpp/language/access">成员访问说明符</a>从基类派生时，基类的所有公开成员可作为派生类的公开成员访问，基类的所有受保护成员可作为派生类的受保护成员访问（基类的私有成员始终不可访问，除非设为友元）。
</p><p>公开继承塑造了面向对象编程的子类型关系：派生类对象是（IS-A）基类对象。到派生类对象的引用和指针，可被期待到其任何公开基类的引用和指针的代码所用（见 <a href="https://en.wikipedia.org/wiki/Liskov_substitution_principle" class="extiw" title="enwiki:Liskov substitution principle">LSP</a>），或者以 <a href="https://en.wikipedia.org/wiki/Design_by_contract" class="extiw" title="enwiki:Design by contract">DbC</a> 的说法，派生类应该维护其公开基类的类不变式，不应强化其所<a href="virtual.html" title="cpp/language/virtual">覆盖</a>的成员函数的任何前条件，或弱化其任何后条件。
</p>
<div class="t-example"><div class="t-example-live-link"><div class="coliru-btn coliru-btn-run-init">运行此代码</div></div>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="co2">#include &lt;vector&gt;</span>
<span class="co2">#include &lt;string&gt;</span>
<span class="co2">#include &lt;iostream&gt;</span>
 
<span class="kw1">struct</span> MenuOption <span class="br0">{</span> <a href="../string/basic_string.html"><span class="kw1230">std::<span class="me2">string</span></span></a> title<span class="sy4">;</span> <span class="br0">}</span><span class="sy4">;</span>
<span class="co1">// Menu 是 MenuOption 的 vector ：能插入、移除、重排……选项并拥有标题。</span>
<span class="kw1">class</span> Menu <span class="sy4">:</span> <span class="kw1">public</span> <a href="../container/vector.html"><span class="kw1269">std::<span class="me2">vector</span></span></a><span class="sy1">&lt;</span>MenuOption<span class="sy1">&gt;</span> <span class="br0">{</span>
<span class="kw1">public</span><span class="sy4">:</span>
    <a href="../string/basic_string.html"><span class="kw1230">std::<span class="me2">string</span></span></a> title<span class="sy4">;</span>
 
    <span class="kw4">void</span> print<span class="br0">(</span><span class="br0">)</span> <span class="kw4">const</span> <span class="br0">{</span>
        <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> title <span class="sy1">&lt;&lt;</span> <span class="st0">":<span class="es1">\n</span>"</span><span class="sy4">;</span>
        <span class="kw1">for</span> <span class="br0">(</span><a href="../types/size_t.html"><span class="kw100">std::<span class="me2">size_t</span></span></a> i <span class="sy1">=</span> <span class="nu0">0</span>, s <span class="sy1">=</span> size<span class="br0">(</span><span class="br0">)</span><span class="sy4">;</span> i <span class="sy1">&lt;</span> s<span class="sy4">;</span> <span class="sy2">++</span>i<span class="br0">)</span>
            <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> <span class="st0">"  "</span> <span class="sy1">&lt;&lt;</span> <span class="br0">(</span>i<span class="sy2">+</span><span class="nu0">1</span><span class="br0">)</span> <span class="sy1">&lt;&lt;</span> <span class="st0">". "</span> <span class="sy1">&lt;&lt;</span> at<span class="br0">(</span>i<span class="br0">)</span>.<span class="me1">title</span> <span class="sy1">&lt;&lt;</span> <span class="st0">'<span class="es1">\n</span>'</span><span class="sy4">;</span>
    <span class="br0">}</span>
<span class="br0">}</span><span class="sy4">;</span>
<span class="co1">// 注： Menu::title 没有问题因为它的角色与基类独立。</span>
 
<span class="kw2">enum</span> <span class="kw1">class</span> Color <span class="br0">{</span> WHITE, RED, BLUE, GREEN <span class="br0">}</span><span class="sy4">;</span>
 
<span class="kw4">void</span> apply_terminal_color<span class="br0">(</span>Color<span class="br0">)</span> <span class="br0">{</span> <span class="coMULTI">/* 操作系统特定 */</span> <span class="br0">}</span>
 
<span class="co1">// 这不好！</span>
<span class="co1">// ColorMenu 是每个选项都有定制颜色的 Menu 。</span>
<span class="kw1">class</span> ColorMenu <span class="sy4">:</span> <span class="kw1">public</span> Menu <span class="br0">{</span>
<span class="kw1">public</span><span class="sy4">:</span>
    <a href="../container/vector.html"><span class="kw1269">std::<span class="me2">vector</span></span></a><span class="sy1">&lt;</span>Color<span class="sy1">&gt;</span> colors<span class="sy4">;</span>
 
    <span class="kw4">void</span> print<span class="br0">(</span><span class="br0">)</span> <span class="kw4">const</span> <span class="br0">{</span>
        <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> title <span class="sy1">&lt;&lt;</span> <span class="st0">":<span class="es1">\n</span>"</span><span class="sy4">;</span>
        <span class="kw1">for</span> <span class="br0">(</span><a href="../types/size_t.html"><span class="kw100">std::<span class="me2">size_t</span></span></a> i <span class="sy1">=</span> <span class="nu0">0</span>, s <span class="sy1">=</span> size<span class="br0">(</span><span class="br0">)</span><span class="sy4">;</span> i <span class="sy1">&lt;</span> s<span class="sy4">;</span> <span class="sy2">++</span>i<span class="br0">)</span> <span class="br0">{</span>
            <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> <span class="st0">"  "</span> <span class="sy1">&lt;&lt;</span> <span class="br0">(</span>i<span class="sy2">+</span><span class="nu0">1</span><span class="br0">)</span> <span class="sy1">&lt;&lt;</span> <span class="st0">". "</span><span class="sy4">;</span>
            apply_terminal_color<span class="br0">(</span>colors<span class="br0">[</span>i<span class="br0">]</span><span class="br0">)</span><span class="sy4">;</span>
            <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> at<span class="br0">(</span>i<span class="br0">)</span>.<span class="me1">title</span> <span class="sy1">&lt;&lt;</span> <span class="st0">'<span class="es1">\n</span>'</span><span class="sy4">;</span>
            apply_terminal_color<span class="br0">(</span>Color<span class="sy4">::</span><span class="me2">WHITE</span><span class="br0">)</span><span class="sy4">;</span>
        <span class="br0">}</span>
    <span class="br0">}</span>
<span class="br0">}</span><span class="sy4">;</span>
<span class="co1">// ColorMenu 需要下列通过公开继承 Menu 无法满足的不变式，例如：</span>
<span class="co1">// - ColorMenu::colors 与 Menu 必须拥有相同数量的元素</span>
<span class="co1">// - 为使得有意义，调用 erase() 也应该从 colors 移除元素以保持选项颜色</span>
<span class="co1">// 基本上每个对 std::vector 的非 const 方法调用都会破坏 ColorMenu 的不变式</span>
<span class="co1">// 并将会需要从用户由正确管理颜色来修复。</span>
 
<span class="kw4">int</span> main<span class="br0">(</span><span class="br0">)</span> <span class="br0">{</span>
    ColorMenu color_menu<span class="sy4">;</span>
 
    <span class="co1">// 这个类的大问题是我们必须保持_Color 与的 Menu 同步。</span>
    color_menu.<span class="me1">push_back</span><span class="br0">(</span>MenuOption<span class="br0">{</span><span class="st0">"某些选择"</span><span class="br0">}</span><span class="br0">)</span><span class="sy4">;</span>
 
    <span class="co1">// color_menu.print(); // 错误！print() 中的 colors[i] 在范围外</span>
 
    color_menu.<span class="me1">colors</span>.<span class="me1">push_back</span><span class="br0">(</span>Color<span class="sy4">::</span><span class="me2">RED</span><span class="br0">)</span><span class="sy4">;</span>
 
    color_menu.<span class="me1">print</span><span class="br0">(</span><span class="br0">)</span><span class="sy4">;</span> <span class="co1">// OK ：colors 与 Menu 拥有相同的元素数</span>
<span class="br0">}</span></pre></div></div>
</div>
<h3><span class="mw-headline" id=".E5.8F.97.E4.BF.9D.E6.8A.A4.E7.BB.A7.E6.89.BF">受保护继承</span></h3>
<p>当类使用 <code>protected</code> <a href="access.html" title="cpp/language/access">成员访问说明符</a>从基类派生时，基类的所有公开和受保护成员可作为派生类的受保护成员访问（基类的私有成员始终不可访问，除非设为友元）。
</p><p>受保护继承可用于“受控制的多态”：在派生类的成员中，以及所有进一步派生的类的成员中，派生类是（IS-A）基类：到派生类的引用和指针可用于期待到基类的引用和指针处。
</p>
<h3><span class="mw-headline" id=".E7.A7.81.E6.9C.89.E7.BB.A7.E6.89.BF">私有继承</span></h3>
<p>当类使用 <code>private</code> <a href="access.html" title="cpp/language/access">成员访问说明符</a>从基类派生时，基类的所有公开和受保护成员可作为派生类的私有成员访问（基类的私有成员始终不可访问，除非设为友元）。
</p><p>私有继承常用于基于策略的设计，因为策略常是空基类，而使用基类可以同时启用静多态并活用<a href="ebo.html" title="cpp/language/ebo">空基类优化</a>
</p><p>私有继承也可以用于实现合成关系（基类子对象是派生类对象的实现细节）。除非派生类需要访问基类的受保护成员（包含构造函数），需要覆盖基类的虚成员，需要基类在某个其他基类子对象之前构造或在其之后销毁，需要共享虚基类或需要控制虚基类的构造，否则使用成员方案可以提供更好的封装，而且通常是更受偏好的方式。使用成员来实现合成关系，亦不适用于从<a href="parameter_pack.html" title="cpp/language/parameter pack">参数包</a>进行多重继承的情况，或在编译时通过模板元编程确定各基类身份的情况。
</p><p>与受保护继承相似，私有继承也可以用于受控制的多态：在派生类的成员内（但不在进一步派生的类中），派生类是（IS-A）基类。
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="kw1">template</span><span class="sy1">&lt;</span><span class="kw1">typename</span> Transport<span class="sy1">&gt;</span>
<span class="kw1">class</span> service <span class="sy4">:</span> <span class="kw1">private</span> Transport  <span class="co1">// 从 Transport 策略私有继承</span>
<span class="br0">{</span>
<span class="kw1">public</span><span class="sy4">:</span>
    <span class="kw4">void</span> transmit<span class="br0">(</span><span class="br0">)</span> <span class="br0">{</span>
        this<span class="sy2">-</span><span class="sy1">&gt;</span>send<span class="br0">(</span>...<span class="br0">)</span><span class="sy4">;</span>  <span class="co1">// 使用 Transport 提供的任何东西进行发送</span>
    <span class="br0">}</span>
<span class="br0">}</span><span class="sy4">;</span>
<span class="co1">// TCP 传输策略</span>
<span class="kw1">class</span> tcp <span class="br0">{</span>
<span class="kw1">public</span><span class="sy4">:</span>
    <span class="kw4">void</span> send<span class="br0">(</span>...<span class="br0">)</span><span class="sy4">;</span>
<span class="br0">}</span><span class="sy4">;</span>
<span class="co1">// UDP 传输策略</span>
<span class="kw1">class</span> udp <span class="br0">{</span>
<span class="kw1">public</span><span class="sy4">:</span>
    <span class="kw4">void</span> send<span class="br0">(</span>...<span class="br0">)</span><span class="sy4">;</span>
<span class="br0">}</span><span class="sy4">;</span>
 
service<span class="sy1">&lt;</span>tcp<span class="sy1">&gt;</span> service<span class="br0">(</span>host, port<span class="br0">)</span><span class="sy4">;</span> 
service.<span class="me1">transmit</span><span class="br0">(</span>...<span class="br0">)</span><span class="sy4">;</span> <span class="co1">// 通过 TCP 发送</span></pre></div></div>
<h3><span class="mw-headline" id=".E6.88.90.E5.91.98.E5.90.8D.E5.AD.97.E6.9F.A5.E6.89.BE">成员名字查找</span></h3>
<p>针对类成员进行的无限定和有限定的名字查找规则，详见于<a href="lookup.html" title="cpp/language/lookup">名字查找</a>。
</p>
<h3><span class="mw-headline" id=".E5.8F.82.E9.98.85">参阅</span></h3>
<ul><li> <a href="virtual.html" title="cpp/language/virtual">虚函数</a>
</li><li> <a href="abstract_class.html" title="cpp/language/abstract class">抽象类</a>
</li></ul>

<!-- 
NewPP limit report
Preprocessor visited node count: 1956/1000000
Preprocessor generated node count: 5447/1000000
Post‐expand include size: 48486/2097152 bytes
Template argument size: 14995/2097152 bytes
Highest expansion depth: 14/40
Expensive parser function count: 0/100
-->

<!-- Saved in parser cache with key mwiki1-mwiki_zh_:pcache:idhash:9252-0!*!0!!zh!*!zh!* and timestamp 20211022194846 -->
</div>                    <!-- /bodycontent -->
                                        <!-- printfooter -->
                    <div class="printfooter">
                    来自“<a href="https://zh.cppreference.com/mwiki/index.php?title=cpp/language/derived_class&amp;oldid=72405">https://zh.cppreference.com/mwiki/index.php?title=cpp/language/derived_class&amp;oldid=72405</a>”                    </div>
                    <!-- /printfooter -->
                                                            <!-- catlinks -->
                    <!-- /catlinks -->
                                                            <div class="visualClear"></div>
                    <!-- debughtml -->
                                        <!-- /debughtml -->
                </div>
                <!-- /bodyContent -->
            </div>
        </div>
        <!-- /content -->
        <!-- footer -->
        <div id="cpp-footer-base" class="noprint">
            <div id="footer">
                        <div id="cpp-navigation">
            <h5>导航</h5>
            <ul><li><a href="https://zh.cppreference.com/w/cpp/language/derived_class">Online version</a></li><li>Offline version retrieved 2022-01-01 00:37.</li></ul></div>
                        <ul id="footer-info">
                                    <li id="footer-info-lastmod"> 本页面最后修改于2021年9月15日 (星期三) 20:49。</li>
                                    <li id="footer-info-viewcount">此页面已被浏览过10,093次。</li>
                            </ul>
                    </div>
        </div>
        <!-- /footer -->
        <script>if(window.mw){
mw.loader.state({"site":"loading","user":"missing","user.groups":"ready"});
}</script>
<script src="../../../common/skin_scripts.js"></script>
<script>if(window.mw){
mw.loader.load(["mediawiki.action.view.postEdit","mediawiki.user","mediawiki.page.ready","mediawiki.searchSuggest","mediawiki.hidpi","ext.gadget.MathJax","ext.gadget.ColiruCompiler"], null, true);
}</script>
<script src="../../../common/site_scripts.js"></script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-2828341-1']);
_gaq.push(['_setDomainName', 'cppreference.com']);
_gaq.push(['_trackPageview']);
</script><!-- Served in 0.926 secs. -->
	</body>
<!-- Cached 20211022194846 -->
</html>